<template>
    <view class="box">
		<!-- tabs -->
		<view class="tabs_colour">
			<van-tabs
				:ellipsis="false"
				:scrollspy="true"
				:animated="true" 
				ref="tabs"
				class="task_tabs"
				color="#fff"
				>
				<van-tab title="基础信息" name="基础信息">
					<!-- 客户信息 -->
					<view class="user_message">
						<view class="user_message_user utils_patternOne">
							<!-- 区块标题 -->
							<view class="utils_title">
								<view class="title_text">
									<text class="title_left_text">客户信息</text>
									<view class="tips"></view>
								</view>
								<!-- 右侧预留位置 -->
								<view class="right_text_title" v-if="personTagArray.length > 0">
									<text @tap="handlePathMore" class="title_right_text">查看更多</text>
								</view>
							</view>
							
							<!-- 客户信息 -->
							<view class="user_message_conetnt">
								<view class="user_conetnt_item">
									<text class="user_content_text">姓名：{{ clientName || '暂无' }}</text>
									<text class="user_content_text">手机号：{{ clientTel || '暂无' }}</text>
								</view>
							</view>
						</view>
						
						<view class="user_message_user utils_patternOne">
							<!-- 区块标题 -->
							<view class="utils_title">
								<view class="title_text">
									<text class="title_left_text">车辆信息</text>
									<view class="tips"></view>
								</view>
								<!-- 右侧预留位置 -->
								<view class="right_text_title" v-if="carTagArray.length > 0">
									<text @tap="handlePathMore" class="title_right_text">查看更多</text>
								</view>
							</view>
							
							<!-- 车辆信息 -->
							<view class="user_message_conetnt">
								<view class="user_conetnt_item">
									
									<text class="user_content_text">车型：{{ carType || '暂无' }}</text>
									<text class="user_content_text">
										车牌号：{{ lsn || '暂无' }}
										<text 
											v-if="lsn"
											@tap="handleCopy(lsn)" 
											class="user_cart_copy"
											>
											复制
										</text>
									</text>
									
								</view>
							</view>
						</view>
					</view>
					
					<!-- 历史工单区域 -->
					<view class="history_work_order">
						<view class="utils_patternOne history_order_left">
							<view class="utils_title">
								<view class="title_text">
									<text class="title_left_text">历史工单</text>
									<view class="tips"></view>
								</view>
							</view>
							
							<!-- 内容 -->
							<view class="history_work_text">
								<text class="work_text">维修项目：</text>
								<!-- <text class="work_text">{{historyOrderTableData.}}</text> -->
								<text v-if="historyOrderTableData.length > 0">{{historyOrderTableData[0].repairType}}</text>
								<text v-else>暂无</text>
							</view>
							<view class="history_work_btn">
								<view @tap="handleGoHistoryPath('历史工单')" class="utils_more_btn">
									查看更多
								</view>
							</view>
						</view>
						
						<view class="history_order_right">
							<view class="utils_title utils_patternOne history_right_top">
								<view class="title_text">
									<text class="title_left_text">招揽记录</text>
									<view class="tips"></view>
								</view>
								<view @tap="handleGoHistoryPath('招揽记录')" class="utils_more_btn">
									更多
								</view>
							</view>
							
							<view class="utils_title utils_patternOne history_right_bottom">
								<view class="title_text">
									<text class="title_left_text">投诉记录</text>
									<view class="tips"></view>
								</view>
								
								<view @tap="handleGoHistoryPath('投诉记录')" class="utils_more_btn">
									更多
								</view>
							</view>
						</view>
						
					</view>
					
					<!-- 任务合并 -->
					<view class="utils_patternOne task_merge">
						<view class="utils_title">
							<view class="title_text">
								<text class="title_left_text">任务合并</text>
								<view class="tips"></view>
							</view>
						</view>
						<view class="task_merge_content">
							<view class="task_merge_items" v-for="(item, index) in relatedTaskList" :key="item.id">
								<view class="taskType_items_left">
									<text class="taskType_text">任务类型:</text>
									<text class="taskType_text">{{item.type}}</text>
								</view>
								<view class="taskType_items_right">
									<text>{{item.taskDate}}</text>
								</view>
							</view>
						</view>
					</view>
					
				</van-tab>
				
				
				<van-tab title="产品推荐">
					<view class="tabs-products">
						<view class="product-header-items">
							<view class="product-header-item">
								<view class="header-item-title">重点检查项</view>
								<view class="header-item-content">
									<view class="item-content-num">{{keyCheckNum}}</view>
									<view class="item-content-unit">项</view>
								</view>
								<view class="header-item-bottom">
									<view class="item-bottom-detail" @click="getPartsDetail(0)">查看</view>
									<van-icon class="item-bottom-arrow" name="arrow" />
								</view>
							</view>

							<view class="product-header-item">
								<view class="header-item-title">待更换KV件</view>
								<view class="header-item-content">
									<view class="item-content-num">{{ kpPartsTableDataKpNum }}</view>
									<view class="item-content-unit">项</view>
								</view>
								<view class="header-item-bottom">
									<view class="item-bottom-detail" @click="getPartsDetail(1)">查看</view>
									<van-icon class="item-bottom-arrow" name="arrow" />
								</view>
							</view>

							<view class="product-header-item">
								<view class="header-item-title">留存问题</view>
								<view class="header-item-content">
									<view class="item-content-num">{{ kpPartsTableDataRemNum }}</view>
									<view class="item-content-unit">项</view>
								</view>
								<view class="header-item-bottom">
									<view class="item-bottom-detail" @click="getPartsDetail(2)">查看</view>
									<van-icon class="item-bottom-arrow" name="arrow" />
								</view>
							</view>
						</view>

						<!-- 推荐产品 -->
						<view class="product-recommend-items">
							<view class="recommend-title">
								<view class="recommend-title-label">推</view>
								<view class="recommend-title-text">推荐产品</view>
							</view>

							<view class="recommend-list">
								<view class="recommend-item" :class="{'active': productIndex === index}"
									v-for="(item, index) in productList" :key="index"
									@click="handleProductIndex(index, item)">
									<view class="recommend-item-left">
										<view class="item-unit">{{index + 1}}</view>
										<view class="item-product-name">{{item.result}}</view>
									</view>
									<view class="item-product-level">{{item.grade}}</view>
								</view>
							</view>
						</view>

						<!-- 沟通用词 -->
						<view class="product-word-items">
							<view class="word-title">沟通用词</view>
							<view class="word-list">
								<view class="word-item" v-for="(item, index) in connectList" :key="index">
									<view class="word-name">{{item.comVocabulary}}</view>
									<view class="word-item-right">
										<van-icon class="item-right-arrow" name="arrow-up" />
										<view class="word-rate">{{item.successRate}}</view>
									</view>
								</view>
							</view>
						</view>


						<!-- 权益推荐 -->
						<view class="equity-word-items">
							<view class="word-title">权益推荐</view>
							<view class="word-list">
								<view class="word-item" v-for="(item, index) in equityList" :key="index">
									<view class="word-name">{{item.activity}}</view>
									<view class="word-item-right">
										<van-icon class="item-right-arrow" name="arrow-up" />
										<view class="word-rate">{{!item.recommendIndex ? '0' : item.recommendIndex}}
										</view>
									</view>
								</view>
							</view>
						</view>

						<!-- 沟通纲要 -->
						<view class="communication-items">
							<view class="word-title">沟通纲要</view>
							<view class="communication-list">
								<view class="communication-item" v-for="(item, index) in text" :key="index">
									<view class="item-left-circle"></view>
									<view class="communication-text">{{item}}</view>
								</view>
							</view>
						</view>
					</view>

				</van-tab>

				<van-tab title="产品辅助">
					<view class="tabs-subsidiary">

						<!-- 知识库 -->
						<view class="knowledge-base-items">
							<view class="word-title">知识库</view>
							<view class="word-search">
								<input class="search-input" v-model="knowledge" type="text" placeholder="输入查询信息">
								<view class="search-btn" @click="queryKnowledge">查询</view>
							</view>

							<view class="knowledge-history-word-items">
								<view class="history-word-item" @click="queryHistoryKnowledge('不按周期保养是否脱保')">不按周期保养是否脱保
								</view>
								<view class="history-word-item" @click="queryHistoryKnowledge('如何查询下次保养时间')">如何查询下次保养时间
								</view>
							</view>

							<view class="knowledge-answer" v-for="(item, index) in knowledgeResultList" :key="index">
								<view class="knowledge-name">{{item.name}}</view>
								<view class="knowledge-answer-text">
									{{ item.description }}
								</view>
							</view>
						</view>

						<!-- 信息生成器 -->
						<view class="info-generation-items">
							<view class="word-title">信息生成器</view>
							<view class="info-generation-word" v-if="isGeneration">{{productRequestList.text_Recommend}}
							</view>
							<view class="info-generation-word" v-else>{{productRequestList.text_Introduce}}</view>
							<view class="info-generation-btns">
								<view class="left-btns">
									<view class="btn-1" @click="isGeneration = true">产品推荐</view>
									<view class="btn-1" @click="isGeneration = false">产品介绍</view>
								</view>

								<view class="right-btns">
									<view class="btn-2" @click="handleNotification">短信推送</view>
								</view>
							</view>
						</view>

						<!-- 产品素材 -->
						<view class="product-image-items">
							<view class="word-title">产品素材</view>
							<view class="product-image-src">
								<!-- <van-image class="image-item" width="100%" height="100%" fit="cover"
									:src="productRequestList.material"></van-image> -->
									<image 
										class="image-item" 
										width="100%" 
										height="100%" 
										:src="productRequestList.material" 
										>
									</image>
							</view>
							<view class="product-image-word">
								{{productRequestList.text_Recommend}}
							</view>
							<view class="product-image-btns">
								<view class="btn-1 large" @click="saveImage">保存至相册</view>
							</view>
						</view>
					</view>

				</van-tab>
			</van-tabs>
		</view>
	
		<!-- 填写跟进结果 -->
		<view class="handOut-btn" v-if="history !== 'history'">
			<button 
				@tap="handleGoPath"
				size="default" 
				type="default"
				class="btn"
				>
				填写跟进结果
			</button>
		</view>
		
	</view>
</template>

<script>
import apiRqs from '@/api/api-request.js'
import utils from '@/utils/uitils.js'
export default {
    data () {
		return {
			vin: '',
			taskId: '',
			groupId: '',
			history: '',
			clientName: '', // 客户姓名
			clientTel: '', // 客户电话
			carType: '', // 车型
			lsn: '', // 车牌号
			personTagArray: [
				{name:'姓名', value: '刘西栅'},
				{name:'手机号', value: '18899992222'},
			],
			carTagArray: [
				{ name: '车牌号', value: '粤B888888' },
				{ name: '车架号', value: 'LMGJS1G85J1122794' },
				{ name: '车型', value: '宝马7系' },
				{ name: '车龄', value: '2年以内' },
				{ name: '购车门店', value: '广汽传奇' },
				{ name: '开票日期', value: '2021-08-01' },
				{ name: '车机里程', value: '10000公里' },
				{ name: '车机截止日期', value: '2021-08-31' },
			],
			historyOrderTableData: [],
			historyOrderReqData: {
				vin: "",
				single: 0,
				pageNumber: 1,
				pageSize: 5,
			},
			relatedTaskList: [],
			routerPath: '', // 填写招揽结果后返回页面的路由
			
			keyCheckNum: 0,
			keyCheckData: [],
			kpWordsList: [],
			kpPartsTableData: [],
			kpPartsTableDataKpNum: 0,
			kpPartsTableDataRemNum: 0,
			initialCusInfoData: [],
			productList: [],
			selectProductName: "",
			productIndex: 0,
			connectList: [],
			equityList: [],
			text: [],
			productRequestList: {},
			isGeneration: true,
			knowledge: "车门把手有划痕",
			knowledgeResultList: [],
		}
	},
	
	onLoad (options) {
		this.vin = options.vin
		this.taskId = options.taskId
		this.groupId = options.groupId
		this.history = options.mode || this.history
		
		this.historyOrderReqData.vin = options.vin
		
		this.routerPath = options.routerPath ? options.routerPath : this.routerPath
	},

    created () {
		// this.historyOrderReqData.vin = this.vin
		// this.shopList = require('../../utils/ShopList.json') // 所有门店信息
		// if (uni.getStorageSync('knowledgeQueryCache')) {
		//     this.historyKnowledge = uni.getStorageSync('knowledgeQueryCache')
		// }
		
		// const kpWordsList = require('../../utils/kpWords.json')
		// this.kpWordsList = kpWordsList.data
		
		// const tokenInfo = uni.getStorageSync('tokenInfo')
		// this.shopId = tokenInfo.shopId
		// this.userMobile = tokenInfo.userMobile || this.userMobile
		const kpWordsList = require('../../utils/kpWords.json') // KV件、留存问题知识仓库
		this.kpWordsList = kpWordsList.data;
    },

    async mounted() {
		await this.getcClientInfo()
		this.getCusWildMaintainRecrd()
		this.getTaskTypeAndScript()
		
		this.getKeyCheckItem();
		this.getCarRetentionProblem();
		this.getProductList();
    },
	
	methods: {
		// 获取客户信息
		async getcClientInfo () {
			try {
				this.personTagArray = []
				this.carTagArray = []

				let reqData = {
					name: '',
					tel: '',
					vin: this.vin,
					lsn: '',
					carType: '', // 车型
					vehicleAgeY: '', // 车龄
					transactionPossibe: '', // 成交可能性
					lastReturnFactoryType: '', // 最后一次返厂类型
					oneLevelId: '',
					twoLevelId: '',
					brandName: '',
					// 上次购买养护品时间
					lastPurchaseTime: {
						beginDate: '2022-01-01',
						endDate: '2024-09-07',
					},
					// 最后一次返厂时间
					lastReturnFactoryTime: {
						beginDate: '2022-01-01',
						endDate: '2024-09-07'
					},
					paged: {
						pageSize: 20,
						pageIndex: 1,
						orderBy: '',
					}
				}

				const res = await apiRqs.getSearchFindService(reqData)
				console.log('获取客户信息res', res.data);

				if (res.data.data.length > 0) {
					const result = JSON.parse(JSON.stringify(res.data));
					console.log('获取客户信息', result);

					// 提取客户姓名、电话、车牌号、车型
					let name = result.data[0].name
					let tel = result.data[0].tel

					this.clientName = name
					this.clientTel = tel
					this.lsn = result.data[0].lsn
					this.carType = result.data[0].carType

					this.personTagArray = [
					    { name: '姓名', value: result.data[0].name || '--' },
					    { name: '手机号', value: result.data[0].tel || '--' },
					];
					
					this.carTagArray = [
					    { name: '车牌号', value: result.data[0].lsn || '--' },
					    { name: '车架号', value: result.data[0].vin || '--' },
					    { name: '车型', value: '比亚迪 ' + (result.data[0].carType || '--') },
					    { name: '车龄', value: result.data[0].vehicleAgeY ? result.data[0].vehicleAgeY + '以内' : '--' },
					    { name: '购车门店', value: result.data[0].shopId || '--' },
					    { name: '开票日期', value: result.data[0].lastPurchaseTime || '--' },
					    { name: '最后一次返厂时间', value: result.data[0].lastReturnFactoryTime || '--' },
					];
					
				}
				
				// 将基础信息结果保存保存起来
				uni.setStorageSync('personTagArray', this.personTagArray)
				uni.setStorageSync('carTagArray', this.carTagArray)

			} catch (error) {
				console.error("获取客户信息失败", error);
			}
		},
		
		// 获取全网历史工单
		async getCusWildMaintainRecrd() {
			try {
				const res = await apiRqs.getCusMaintainRecord(this.historyOrderReqData);
				const result = JSON.parse(JSON.stringify(res.data));
				console.log("历史工单arr", res.data);
			
				for (let i = 0; i < result.data.length; i++) {
					result.data[i].odo = utils.textFormat(result.data[i].odo.toFixed(0)) + 'km'
					result.data[i].amount = result.data[i].amount + "元";
					result.data[i].amountReceivable = result.data[i].amountReceivable + "元";
				}
				this.historyOrderTableData = result.data;
				console.log("历史工单resultdata", result.data);
				
				// this.historyOrderTotal = result.totalRecords;
			} catch (err) {
				console.error("历史工单报错", err);
			}
		},
		
		// 获取维系任务
		async getTaskTypeAndScript () {
			try {
				let reqData1 = {
					taskId: this.taskId,
					vin: this.vin,
				}

				const res = await apiRqs.getTaskBatchList(reqData1)
				console.log('连带维系项目列表', res)

				const newRes = JSON.parse(JSON.stringify(res.data))
				
				const taskTypeList = newRes.map((item) => {
					if (item.taskDate) {
						item.taskDate = item.taskDate.split(' ')[0]
					}
					// if (
					// 	item.type.includes('定保') &&
					// 	this.carDayNum < 180 &&
					// 	(this.maintainTimes === 0 || this.maintainTimes === '0')
					// ) {
					// 	item.type = '首保招揽'
					// 	console.log(
					// 		'满足条件',
					// 		item.type,
					// 		this.carDayNum,
					// 		this.maintainTimes,
					// 		'定保改为首保招揽'
					// 	)
					// }
					return item.taskType
				})

				const updatedTasks = newRes.map((task) => {
					// if (
					// 	task.type.includes('定保') &&
					// 	this.carDayNum < 180 &&
					// 	(this.maintainTimes === 0 || this.maintainTimes === '0')
					// ) {
					// 	console.log(
					// 		'满足条件',
					// 		task.type,
					// 		this.carDayNum,
					// 		this.maintainTimes,
					// 		'定保改为首保招揽'
					// 	)
					// 	return {
					// 		...task,
					// 		type: '首保招揽'
					// 	}
					// } else {
					// 	return task
					// }
					return task
				})

				// updatedTasks数组中处理日期格式去除beginKeepDate属性中的时分秒
				updatedTasks.map(item => {
					if (item.beginKeepDate) {
						item.beginKeepDate = item.beginKeepDate.split(' ')[0]
					}
					return item
				})
				console.log('招揽事项updatedTasks ------', updatedTasks)
				
				this.taskTypeList = taskTypeList
				this.relatedTaskList = updatedTasks

				this.relatedTaskList.forEach(item => {
					// 将taskDate日期提取年份
					let date = item.taskDate.split('-')[0]
					console.log('item.taskDate', item.taskDate)
					if (date === '1753') {
						item.taskDate = item.beginKeepDate
					}
					
					// 替换属性为null的值为""
					for (let key in item) {
						if (item[key] === null) {
							item[key] = "--";
						}
					}
				})

				// 当招揽任务数只有 1 个时，默认选中当前任务
				// if (updatedTasks.length == 1) {
				// 	this.checkList = [updatedTasks[0].id];
				// }

			} catch (e) {
				console.log('获取连带维系项目列表失败', e)
			}
		},
		
		// 跳转跟进结果填写页面
		handleGoPath() {
			uni.navigateTo({
				url: '/packageE/maintenance-task/follow-results?vin=' + 
					this.vin + '&taskId=' + this.taskId + '&routerPath=' + this.routerPath
			})
		},
		// 基础信息跳转
		handlePathMore() {
			uni.navigateTo({
				url: '/packageE/maintenance-task/subset-page/basics-message'
			})
		},
		// 历史工单区域跳转
		handleGoHistoryPath(name) {
			if(name === '历史工单') {
				uni.navigateTo({
					url: '/packageE/maintenance-task/subset-page/history-single?vin=' + this.vin
				})
			}
			else if(name === '招揽记录') {
				uni.navigateTo({
					url: '/packageE/maintenance-task/subset-page/solicit-records?vin=' + this.vin
				})
			}
			else if(name === '投诉记录') {
				uni.navigateTo({
					url: '/packageE/maintenance-task/subset-page/complain-records?vin=' + this.vin
				})
			}
			
		},
		
		// 复制车架号
		handleCopy(value) {
			console.log('被复制的车架号', value)
			uni.setClipboardData({
				data: value,
				success: function(res) {
					uni.getClipboardData({
						success: function(res) {
							uni.showToast({
								title: "复制成功",
							});
						},
						complete: function(res) {
							console.log('复制车架号res', res)
						}
					});
				},
				complete: function(res) {
					console.log('复制车架号res1023', res)
				}
			});
		},
		
		// 重点检查项
		async getKeyCheckItem() {
			try {
				const res = await apiRqs.getKeyCheckItem(this.vin);
				console.log("重点检查项 result", res);
				if (res.code === 200) {
					const data = res.data;

					// 提取函数用于赋值
					const assignValues = (target, sourceList) => {
						for (let i = 0; i < target.length; i++) {
							for (let y = 0; y < sourceList.length; y++) {
								if (target[i].name == sourceList[y].name) {
									target[i].function = sourceList[y].function;
									target[i].benefits = sourceList[y].benefits;
									target[i].care = sourceList[y].care;
								}
							}
						}
					};

					assignValues(data, this.kpWordsList);

					this.keyCheckNum = data.length;
					this.keyCheckData = data;
				}
			} catch (err) {
				console.log('err', err);
			}
		},
		// 待更换 KV 件
		async getCarRetentionProblem() {
			try {
				const initialCusInfoData = this.initialCusInfoData;

				let vehicleMileage = null; // 车机里程
				let lastGuaranteedMileage = null; // 上次定保里程
				for (const obj of initialCusInfoData) {
					if (obj.name === "车机里程") {
						vehicleMileage = obj.value;
					} else if (obj.name === "上次定保里程") {
						lastGuaranteedMileage = obj.value;
					}
				}
				const retentionReqData = {
					odo: 0,
					vin: this.vin,
				}

				if (vehicleMileage) {
					retentionReqData.odo = vehicleMileage.split("~")[1] * 1;
				} else if (!vehicleMileage && lastGuaranteedMileage) {
					retentionReqData.odo = lastGuaranteedMileage * 1;
				} else {
					retentionReqData.odo = 0;
				}
				const res = await apiRqs.getCarRetentionProblem(
					retentionReqData
				);
				console.log("待更换 KV 件、留存问题  未处理前", res);
				let newArr = JSON.parse(JSON.stringify(res.data));

				// 提取函数用于赋值
				const assignValues = (target, sourceList) => {
					console.log('提取函数用于赋值', target, sourceList);
					for (let i = 0; i < target.length; i++) {
						for (let y = 0; y < sourceList.length; y++) {
							if (target[i].name == sourceList[y].name) {
								target[i].function = sourceList[y].function;
								target[i].benefits = sourceList[y].benefits;
								target[i].care = sourceList[y].care;
							}
						}
					}
				};

				// KV件要点赋值
				assignValues(newArr.kp, this.kpWordsList);
				// 留存问题要点赋值
				assignValues(newArr.remainParts, this.kpWordsList);

				this.kpPartsTableData = newArr;
				this.kpPartsTableDataKpNum = this.kpPartsTableData.kp.length;
				this.kpPartsTableDataRemNum = this.kpPartsTableData.remainParts.length;
				console.log("-------------- 待更换KV件、留存问题 --------------", this.kpPartsTableData);
			} catch (err) {
				console.error("-------------- 待更换KV件、留存问题 --------------", err);
			}
		},
		// 获取产品推荐列表
		async getProductList() {
			try {
				const res = await apiRqs.getProductService({
					vin: this.vin
				});
				console.log('获取产品推荐列表', res);
				const data = res.data;
				// 进行排序将grade为高的排在最前面其次是中最后是低
				this.productList = data.sort((a, b) => {
					if (a.grade === '高') {
						return -1;
					} else if (a.grade === '中' && b.grade !== '高') {
						return -1;
					} else {
						return 1;
					}
				});
				console.log('排序后', this.productList);

				// 将productList固定显示为前三条
				this.productList = this.productList.slice(0, 3);
				console.log('固定显示前三条', this.productList);

				this.selectProductName = this.productList[0].result;

				// 初始化信息生成器、产品素材
				this.handleProductRequest(this.productList[0].result)

				// 初始化沟通用词
				this.initCommunicationWords(this.productList[0].result)

			} catch (error) {
				console.error('获取产品推荐列表失败', error);
			}
		},
		// 点击产品推荐列表
		async handleProductIndex(index, item) {
			this.productIndex = index;
			console.log('items', item.result);
			this.selectProductName = item.result;
			// 发起请求
			this.handleProductRequest(item.result);
			// this.getProductMaterial(item.result)
			this.initCommunicationWords(item.result)
		},
		// 初始化沟通用词、权益推荐、沟通纲要
		async initCommunicationWords(select) {
			try {
				let reqData = {
					vin: this.vin,
					select,
				}
				const req = await apiRqs.getGenerateService(reqData);
				const res = req.data;
				console.log('沟通用词', res);

				// 提取沟通用词列表
				// 将res.connectList中的successRate乘以100 保留两位小数不进行四舍五入
				for (let i = 0; i < res.connectList.length; i++) {
					if (res.connectList[i].successRate !== 0 || res.connectList[i].successRate !== null) {
						res.connectList[i].successRate = (res.connectList[i].successRate * 100).toFixed(2) + "%";
					} else {
						res.connectList[i].successRate = "0%";
					}
				}

				res.connectList.sort((a, b) => {
					let successRateA = parseFloat(a.successRate);
					let successRateB = parseFloat(b.successRate);

					if (successRateA > successRateB) {
						return -1;
					} else if (successRateA < successRateB) {
						return 1;
					} else {
						return 0;
					}
				});

				this.connectList = res.connectList

				// 提取权益推荐列表
				for (let i = 0; i < res.equityList.length; i++) {
					if (res.equityList[i].recommendIndex !== 0 || res.equityList[i].recommendIndex !== null) {
						res.equityList[i].recommendIndex = (res.equityList[i].recommendIndex * 100).toFixed(2) +
							"%";
					} else {
						res.equityList[i].recommendIndex = "0%";
					}
				}

				res.equityList.sort((a, b) => {
					let successRateA = parseFloat(a.recommendIndex);
					let successRateB = parseFloat(b.recommendIndex);

					if (successRateA > successRateB) {
						return -1;
					} else if (successRateA < successRateB) {
						return 1;
					} else {
						return 0;
					}
				});

				this.equityList = res.equityList


				// 提取沟通纲要列表
				// 将res.text[0].commGuidelines中的内容按\n分割为数组

				if (res.text.length > 0) {
					res.text[0].commGuidelines = res.text[0].commGuidelines.split(";");
					console.log("沟通纲要", res.text[0].commGuidelines);
					this.text = res.text[0].commGuidelines;
				} else if (res.text.length === 0) {
					this.text = [];
				}
			} catch (error) {
				console.error('初始化沟通用词失败', error);
			}
		},
		// 点击产品推荐列表后发起请求  获取信息生成器、产品素材
		async handleProductRequest(select) {
			try {
				let reqData = {
					vin: this.vin,
					select,
				}
				const res = await apiRqs.getProductMaterialService(reqData);
				console.log('信息生成器、产品素材', res);

				this.productRequestList = res.data;

			} catch (error) {
				console.error('请求失败', error);
			}
		},
		// 短信推送
		handleNotification() {
			uni.showModal({
				title: "短信推送",
				content: "确认进行短信推送?",
				confirmText: "确认发送",
				success(res) {
					if (res.confirm) {
						uni.showToast({
							title: "发送成功"
						})
					}
				},
			})
		},
		// 保存至相册
		saveImage() {
			uni.showToast({
				title: "已保存至相册"
			})

		},
		// 知识库查询
		queryKnowledge() {
			const knowledge = this.knowledge;
			if (knowledge.trim() === "") {
				uni.showToast({
					title: "请输入查询内容"
				})
				return;
			}
			// const historyKnowledge = this.historyKnowledge;
			// console.log('historyKnowledge', historyKnowledge);
			// if (historyKnowledge.length > 5) {
			// 	historyKnowledge.splice(historyKnowledge.length - 1, 1);
			// 	historyKnowledge.unshift(knowledge);
			// } else {
			// 	historyKnowledge.unshift(knowledge);
			// }
			// this.historyKnowledge = historyKnowledge;
			// localStorage.setItem("knowledgeQueryCache", JSON.stringify(historyKnowledge));
			// this.knowledgeLoading = true;
			uni.showLoading({
				title: "加载中"
			})
			apiRqs.queryknowledges(knowledge)
				.then((res) => {
					// this.knowledgeLoading = false;
					uni.hideLoading();
					console.log("知识库查询结果", res);
					const newRes = JSON.parse(JSON.stringify(res.data));
					this.knowledgeResultList = newRes;

					// let dataTracking = {
					//     createTime: this.GLOBAL.dateTimeStr("y-m-d h:i:s"),
					//     eventType: "click",
					//     from: "gac_web_strategy",
					//     clickId: "strategy_4",
					//     clickName: `【12-5】策略库-知识库查询-查询标题：${knowledge}_${this.vin}`,
					// };
					// // 埋点
					// this.GLOBAL.handleTracking([dataTracking]);
				})
				.catch((err) => {
					// this.knowledgeLoading = false;
					uni.hideLoading();
					uni.showToast({
						title: err
					})
					console.error('知识库查询失败', err);
				});
		},
		// 历史知识查询
		queryHistoryKnowledge(txt) {
			uni.showLoading({
				title: "加载中"
			})
			apiRqs.queryknowledges(txt)
				.then((res) => {
					uni.hideLoading();
					const newRes = JSON.parse(JSON.stringify(res.data));
					this.knowledgeResultList = newRes;
				})
				.catch((err) => {
					uni.hideLoading();
					uni.showToast({
						title: err
					})
					console.error('知识库查询失败', err);
				});
		},
		// 查看重点检查项、留存问题、待更换 KV 件明细
		getPartsDetail(idx) {
			const keyCheckData = this.keyCheckData;
			const kvParts = this.kpPartsTableData.kp;
			const problemParts = this.kpPartsTableData.remainParts;
			if (idx === 0) {
				uni.setStorageSync("partsDetail", keyCheckData);
			} else if (idx === 1) {
				uni.setStorageSync("partsDetail", kvParts);
			} else {
				uni.setStorageSync("partsDetail", problemParts);
			}
			uni.setStorageSync("partsDetailId", idx);
			uni.navigateTo({
				url: "/packageE/parts-detail/parts-detail"
			})
		},
	},
}
</script>

<style lang="less" scoped>
	.box {
		// height: 100%;
		// background-color: #f7f8fa;
		.tabs_colour {
			display: flex;
			flex-direction: column;
			flex: 1;
			background-image: url('../../static/byd-img/jiaoji@1x.png');
			background-repeat: no-repeat;
			/* 将背景图位置设置为顶部居中 */
			background-position: top center; 
			/* 根据不同宽度适配图片宽 */
			background-size: contain; 
			width: 100%;
			height: 100%;
			
			/* 公共样式-内外边距、背景色、边框弧度 */
			.utils_patternOne {
				margin-bottom: 32rpx;
				padding: 24rpx;
				border-radius: 16rpx;
				background-color: #fff;
			}
			
			/* 公共样式-区块标题 */
			.utils_title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;
				
				.title_text {
					position: relative;
					font-size: 32rpx;
					font-weight: 500;
					color: #1D2129;
					.title_left_text {
						margin-left: 24rpx;
					}
					.tips {
						position: absolute;
						top: 10rpx;
						left: 0;
						border-radius: 8rpx;
						width: 8rpx;
						height: 24rpx;
						background: #0063FF;
					}
				}
				
				.right_text_title {
					font-size: 24rpx;
					color: #86909C;
				}
			}
			
			/* 公共样式-查看更多按钮 */
			.utils_more_btn {
				padding: 10rpx 10rpx;
				border-radius: 24rpx;
				background-color: #0063FF;
				font-size: 24rpx;
				color: #FFFFFF;
			}
			
			.user_message,
			.history_work_order,
			.task_merge {
				margin-right: 24rpx;
				margin-left: 24rpx;
			}
			
			/* 客户基础信息 */
			.user_message {
				margin-top: 32rpx;
				.user_message_user {
					.user_message_conetnt {
						.user_conetnt_item {
							display: flex;
							justify-content: space-between;
							align-items: center;
							flex-wrap: wrap;	
							font-family: 思源黑体;
							font-size: 28rpx;
							color: #4E5969;
							
							.user_content_text {
								margin-bottom: 24rpx;
								// display: flex;
								// align-items: center;
								// white-space: nowrap;
								.user_cart_copy {
									margin-left: 20rpx;
									color: #0063FF;
								}
							}
							
						}
					}
				}
			}
			
			/* 历史工单区域 */
			.history_work_order {
				display: flex;
				justify-content: space-between;
				// padding: 0 32rpx 0 32rpx;
				.history_order_left {
					flex: 1;
					margin-right: 24rpx;
					background-image: url('../../static/byd-img/lishigongdan@1x.png');
					background-size: cover;
					background-position: center;
					background-repeat: no-repeat;
					
					.history_work_text {
						display: flex;
						// align-items: center;
						margin-bottom: 24rpx;
						font-size: 28rpx;
						color: #4E5969;
						.work_text {
							white-space: nowrap;
						}
					}
					.history_work_btn {
						display: flex;
						justify-content: flex-end;
					}
				}
				.history_order_right {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-around;
					
					// .history_right_top{
					// 	margin-bottom: 0;
					// }
				}
			}
			
			/* 任务合并 */
			.task_merge {
				.task_merge_content {
					display: flex;
					flex-direction: column;
					.task_merge_items {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 24rpx;
						padding: 24rpx;
						border-radius: 12rpx;
						background: #F7F8FA;
						
						.taskType_items_left {
							.taskType_text {
								font-family: 思源黑体;
								font-size: 28rpx;
								font-weight: 400;
								color: #4E5969;
								
								&:last-child {
									margin-left: 10rpx;
									font-weight: 700;
								}
							}
						}
						
						.taskType_items_right {
							font-family: 思源黑体;
							font-size: 24rpx;
							color: #4E5969;
						}
						
						&:last-child {
							margin-bottom: 0rpx;
						}
					}
				}
			}
			
		}
		
		.tabs-products {
			.product-header-items {
				display: flex;
				align-items: center;
				margin: 24rpx;

				.product-header-item {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					min-width: 0;
					height: 248rpx;
					padding: 24rpx;
					box-sizing: border-box;
					background-color: #fff;
					background-image: url("https://bydapi.vaubang.cn/UploadFiles/Images/byd/detail-item-bg.png");
					background-repeat: no-repeat;
					background-size: 100%;
					background-position: top;
					border-radius: 16rpx;
					margin-right: 24rpx;

					&:last-child {
						margin-right: 0;
					}

					.header-item-title {
						font-size: 28rpx;
						color: #1D2129;
						display: flex;
						align-items: center;

						&::before {
							display: inline-block;
							content: "";
							width: 8rpx;
							height: 24rpx;
							background-color: #0063FF;
							margin-right: 16rpx;
							border-radius: 8rpx;
						}
					}

					.header-item-content {
						display: flex;
						justify-content: center;

						.item-content-num {
							font-size: 64rpx;
							color: #0063FF;
							font-weight: bold;
						}

						.item-content-unit {
							font-size: 24rpx;
							color: #1D2129;
							margin-left: 6rpx;
							margin-top: 40rpx;
						}
					}

					.header-item-bottom {
						display: flex;
						align-items: center;
						justify-content: flex-end;

						.item-bottom-detail {
							font-size: 24rpx;
							color: #86909C;
						}

						.item-bottom-arrow {
							font-size: 24rpx;
							color: #86909C;
						}
					}
				}
			}

			.product-recommend-items {
				background: linear-gradient(270deg, #DFEBFF 1%, #FEFEFF 100%);
				margin: 24rpx;
				padding: 24rpx;
				border-radius: 16rpx;

				.recommend-title {
					display: flex;
					align-items: center;

					.recommend-title-label {
						width: 64rpx;
						height: 64rpx;
						text-align: center;
						line-height: 64rpx;
						border-radius: 8px;
						background: #0063FF;
						border: 2px solid rgba(0, 99, 255, 0.1);
						font-size: 32rpx;
						font-weight: bold;
						color: #fff;
						margin-right: 16rpx;
					}

					.recommend-title-text {
						font-size: 32rpx;
						color: #1D2129;
					}
				}

				.recommend-list {
					.recommend-item {
						margin-top: 24rpx;
						padding: 16rpx 24rpx;
						box-sizing: border-box;
						border-radius: 16rpx;
						background-color: #fff;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.recommend-item-left {
							display: flex;
							align-items: center;
							margin-right: 40rpx;

							.item-unit {
								font-size: 40rpx;
								color: #1D2129;
								font-weight: bold;
							}

							.item-product-name {
								font-size: 28rpx;
								color: #1D2129;
								margin-left: 20rpx;
							}
						}

						.item-product-level {
							color: #1D2129;
							font-size: 40rpx;
							font-weight: bold;
						}

						&.active {
							background-color: #0063FF;

							.recommend-item-left {

								.item-unit,
								.item-product-name {
									color: #fff;
								}
							}

							.item-product-level {
								color: #fff;
							}
						}
					}
				}
			}

			.product-word-items,
			.equity-word-items {
				background: linear-gradient(270deg, #DFEBFF 1%, #FEFEFF 100%);
				margin: 24rpx;
				padding: 24rpx;
				border-radius: 16rpx;

				.word-title {
					font-size: 32rpx;
					color: #1D2129;
					display: flex;
					align-items: center;

					&::before {
						display: inline-block;
						content: "";
						width: 8rpx;
						height: 24rpx;
						background-color: #0063FF;
						margin-right: 16rpx;
						border-radius: 8rpx;
					}
				}

				.word-list {
					.word-item {
						margin-top: 24rpx;
						padding: 16rpx 24rpx;
						box-sizing: border-box;
						border-radius: 16rpx;
						background-color: #fff;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.word-name {
							font-size: 28rpx;
							color: #1D2129;
							margin-right: 40rpx;
						}

						.word-item-right {
							display: flex;
							align-items: center;

							.item-right-arrow {
								font-size: 32rpx;
								color: #0063FF;
								margin-right: 10rpx;
							}

							.word-rate {
								font-size: 36rpx;
								color: #0063FF;
								font-weight: bold;
							}
						}
					}
				}
			}

			.communication-items {
				background: linear-gradient(270deg, #DFEBFF 1%, #FEFEFF 100%);
				margin: 24rpx 24rpx 60rpx 24rpx;
				padding: 24rpx;
				border-radius: 16rpx;

				.word-title {
					font-size: 32rpx;
					color: #1D2129;
					display: flex;
					align-items: center;

					&::before {
						display: inline-block;
						content: "";
						width: 8rpx;
						height: 24rpx;
						background-color: #0063FF;
						margin-right: 16rpx;
						border-radius: 8rpx;
					}
				}

				.communication-list {
					margin-top: 24rpx;
					background-color: #fff;
					border-radius: 16rpx;
					padding: 24rpx;
					box-sizing: border-box;

					.communication-item {
						margin-top: 24rpx;
						display: flex;
						align-items: center;

						&:first-child {
							margin-top: 0;
						}

						.item-left-circle {
							width: 16rpx;
							height: 16rpx;
							background-color: #0063FF;
							border-radius: 50%;
							margin-right: 16rpx;
						}

						.communication-text {
							font-size: 28rpx;
							color: #1D2129;
						}
					}
				}
			}



		}

		.tabs-subsidiary {
			.knowledge-base-items {
				background-color: #fff;
				margin: 24rpx;
				padding: 24rpx;
				border-radius: 16rpx;

				.word-title {
					font-size: 32rpx;
					color: #1D2129;
					display: flex;
					align-items: center;

					&::before {
						display: inline-block;
						content: "";
						width: 8rpx;
						height: 24rpx;
						background-color: #0063FF;
						margin-right: 16rpx;
						border-radius: 8rpx;
					}
				}

				.word-search {
					display: flex;
					align-items: center;
					margin-top: 24rpx;

					.search-input {
						flex: 1;
						min-width: 0;
						border-top-left-radius: 12rpx;
						border-bottom-left-radius: 12rpx;
						height: 64rpx;
						line-height: 64rpx;
						font-size: 28rpx;
						border: 2rpx solid #DFDFDF;
						padding: 0 20rpx;
						box-sizing: border-box;
					}

					.search-btn {
						width: 140rpx;
						flex: 0 0 140rpx;
						height: 64rpx;
						text-align: center;
						line-height: 64rpx;
						background: #0063FF;
						font-size: 28rpx;
						color: #FFFFFF;
						border-top-right-radius: 12rpx;
						border-bottom-right-radius: 12rpx;
						border: 2rpx solid #0063FF;
					}
				}

				.knowledge-history-word-items {
					margin-top: 24rpx;
					display: flex;
					flex-wrap: wrap;

					.history-word-item {
						padding: 10rpx 20rpx;
						background-color: #eee;
						color: #1D2129;
						border-radius: 80rpx;
						font-size: 24rpx;
						margin-right: 20rpx;

						&:last-child {
							margin-right: 0;
						}
					}
				}

				.knowledge-answer {
					background: #fff;
					padding: 24rpx;
					border-radius: 16rpx;
					box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.15);
					margin-top: 24rpx;

					.knowledge-name {
						font-size: 24rpx;
						color: #3D3D3D;
						font-weight: bold;
					}

					.knowledge-answer-text {
						font-size: 24rpx;
						color: #3D3D3D;
						margin-top: 16rpx;
					}
				}
			}

			.info-generation-items {
				background-color: #fff;
				margin: 24rpx;
				padding: 24rpx;
				border-radius: 16rpx;

				.word-title {
					font-size: 32rpx;
					color: #1D2129;
					display: flex;
					align-items: center;

					&::before {
						display: inline-block;
						content: "";
						width: 8rpx;
						height: 24rpx;
						background-color: #0063FF;
						margin-right: 16rpx;
						border-radius: 8rpx;
					}
				}

				.info-generation-word {
					background: #F7F8FA;
					padding: 24rpx;
					box-sizing: border-box;
					border-radius: 12rpx;
					font-size: 24rpx;
					color: #86909C;
					margin-top: 24rpx;
				}

				.info-generation-btns {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-top: 24rpx;

					.left-btns {
						display: flex;
						align-items: center;

						.btn-1 {
							width: 144rpx;
							height: 64rpx;
							text-align: center;
							line-height: 64rpx;
							border: 2rpx solid #0063FF;
							color: #0063FF;
							background: #fff;
							font-size: 28rpx;
							border-radius: 12rpx;
							margin-right: 20rpx;
						}
					}

					.right-btns {
						display: flex;
						align-items: center;

						.btn-2 {
							width: 144rpx;
							height: 64rpx;
							text-align: center;
							line-height: 64rpx;
							border: 2rpx solid #0063FF;
							color: #fff;
							background: #0063FF;
							font-size: 28rpx;
							border-radius: 12rpx;
							margin-left: 20rpx;
						}
					}
				}
			}

			.product-image-items {
				background-color: #fff;
				margin: 24rpx 24rpx 180rpx 24rpx;
				padding: 24rpx;
				border-radius: 16rpx;

				.word-title {
					font-size: 32rpx;
					color: #1D2129;
					display: flex;
					align-items: center;

					&::before {
						display: inline-block;
						content: "";
						width: 8rpx;
						height: 24rpx;
						background-color: #0063FF;
						margin-right: 16rpx;
						border-radius: 8rpx;
					}
				}

				.product-image-src {
					width: 100%;
					height: 400rpx;
					margin-top: 24rpx;

					.image-item {
						width: 100%;
						height: 100%;
					}
				}

				.product-image-word {
					background: #F7F8FA;
					padding: 24rpx;
					box-sizing: border-box;
					border-radius: 12rpx;
					font-size: 24rpx;
					color: #86909C;
					margin-top: 24rpx;
				}

				.product-image-btns {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					margin-top: 24rpx;

					.btn-1 {
						width: 144rpx;
						height: 64rpx;
						text-align: center;
						line-height: 64rpx;
						border: 2rpx solid #0063FF;
						color: #fff;
						background: #0063FF;
						font-size: 28rpx;
						border-radius: 12rpx;
						margin-left: 20rpx;

						&.large {
							width: 200rpx;
						}
					}
				}
			}
		}
		
		/* 跟进结果填写按钮 */
		.handOut-btn {
			position: fixed;
			left: 0;
			bottom: constant(safe-area-inset-bottom);
			bottom: env(safe-area-inset-bottom);
			margin: 0 24rpx 0rpx 24rpx;
			width: calc(100% - 48rpx);
			
			.btn {
				background-color: #0063FF;
				color: #fff;
				font-size: 32rpx;
				font-weight: 600;
			}
		}
		
		/** tabs栏样式 */
		::v-deep .task_tabs {
			.van-tabs--line {
				// background-color: #3378fd;
		
				.van-sticky {
					.van-sticky-wrap {
						// background-color: #3378fd;
		
						.van-tabs__scroll--line {
							background-color: #1476FF;
							.van-tabs__nav--line {
		
								// tabs选中时的底部横线
								.van-tabs__line {
									width: 32rpx !important;
									// background-color: #FF0000;
								}
		
								// tabs未选中时的字体样式
								.van-tab {
									color: #fff;
									font-size: 24rpx;
									font-weight: 400;
								}
		
								// tabs选中时的字体样式
								.van-tab--active {
									color: #fff;
									font-size: 24rpx ;
									font-weight: 600;
								}
							}
						}
					}
				}
			}
		
			// /* 选中状态下的标题样式 */
			// .van-tab--active .normal-tab {
			// 	color: red; /* 设置选中状态下的字体颜色为红色 */
			// }
		
			// /* 未选中状态下的标题样式 */
			// .normal-tab {
			// 	color: black; /* 设置未选中状态下的字体颜色为黑色 */
			// }
		
			// /* 选中状态下的标题样式 */
			// .van-tab--active .custom-tab {
			// 	font-weight: bold; /* 设置选中状态下的字体加粗 */
			// }
		
			// /* 未选中状态下的标题样式 */
			// .custom-tab {
			// 	font-weight: normal; /* 设置未选中状态下的字体正常 */
			// }
		}
	}
</style>
